package org.example.business;

import com.alibaba.fastjson.JSONObject;
import org.example.utils.RequestParseParamsTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;


/**
 *  说明: S_DingDong_Gateway
 * @author author
 * @date 2018年9月10日
 */
@RestController
public class S_Alexa_Gateway {

    private static Logger log = LoggerFactory.getLogger(S_Alexa_Gateway.class);

    @Autowired
    private AlexaHandler alexaHandler;

    @RequestMapping("/alexa/S_Alexa_Gateway/postGateway")
    public Object postGateway(HttpServletRequest request, HttpServletResponse response) throws Exception {

        JSONObject body = RequestParseParamsTool.getParamsFromRequestBody(request);
        log.info("body===>" + body);

        JSONObject jsonObject = GetResponse(body.getString("request"));
        return jsonObject;
    }

    private JSONObject GetResponse(String json) {

        InputStream inputStream = new ByteArrayInputStream(json.getBytes(Charset.forName("UTF-8")) );
        OutputStream outputStream = new OutputStream()
        {
            private StringBuilder sb = new StringBuilder();
            @Override
            public void write(int b) throws IOException {
                this.sb.append((char) b );
            }

            public String toString(){
                return this.sb.toString();
            }
        };

        alexaHandler.handler(inputStream, outputStream, null);

        String responseString = outputStream.toString();
        JSONObject jsonObject = JSONObject.parseObject(responseString);
        return jsonObject;
    }


}